import java.io.File;
import java.io.IOException;
import java.net.BindException;
import java.net.ServerSocket;
import java.net.URL;
import java.security.ProtectionDomain;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;

public class MainWebapp {
	// default contextPath
	private static String contextPath = "/";
	// default port
	private static int port = 6667;

	public static void main(String[] args) throws Exception {

		handlePort(args);
		if (testPort(port))
			throw new BindException("The port:: [" + port + "]  " + "is already in Use...");

		handleContextPath(args);
		runApp();

	}

	// 设置监听端口
	private static void handlePort(String[] args) {
		String _tmp_port = checkPara(args, "port");
		if (null != _tmp_port) {
			String _port = getPara(_tmp_port);
			try {
				port = Integer.parseInt(_port);
			} catch (NumberFormatException e) {
				port = 6667;
			}
		}
	}

	// 设置上下文路径
	private static void handleContextPath(String[] args) {
		String _tmp_port = checkPara(args, "path");
		if (null != _tmp_port) {
			String _path = getPara(_tmp_port);
			try {
				if (_path.startsWith("/")) {
					contextPath = _path;
				} else {
					contextPath = "/" + _path;
				}
			} catch (NumberFormatException e) {
				contextPath = "/";
			}
		}
	}

	// 获取指定参数 1.所有参数 2.指定参数
	private static String checkPara(String[] para, String pointPara) {
		for (int i = 0; i < para.length; i++) {
			if (para[i].startsWith(pointPara)) {
				return para[i];
			}
		}
		return null;
	}

	// 获取参数对应的值
	private static String getPara(String para) {
		return para.substring(para.indexOf("=") + 1);
	}

	private static void runApp() {
		Server server = createServer(contextPath, port);
		try {
			server.start();
			System.out.println(port + "-" + contextPath);
			server.join();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(100);
		}
	}

	private static Server createServer(String contextPath, int port) {
		// use Eclipse JDT compiler
		System.setProperty("org.apache.jasper.compiler.disablejsr199", "true");

		Server server = new Server(port);
		server.setStopAtShutdown(true);

		ProtectionDomain protectionDomain = MainPersistent.class.getProtectionDomain();
		URL location = protectionDomain.getCodeSource().getLocation();

		String warFile = location.toExternalForm();
		WebAppContext context = new WebAppContext(warFile, contextPath);
		context.setServer(server);

		String currentDir = new File(location.getPath()).getParent();
		File workDir = new File(currentDir, "work");
		context.setTempDirectory(workDir);

		server.setHandler(context);
		return server;
	}

	private static boolean testPort(int port) {
		try {
			ServerSocket ss = new ServerSocket(port);
			ss.close();
			return false;
		} catch (IOException e) {
			return true;
		}
	}
}
